<script setup lang="ts">
import { ref, onMounted, computed, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElRadioGroup, ElRadio, ElInput, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import type { UploadFile } from 'element-plus'
import axios from 'axios'

// 配置后端基础地址
axios.defaults.baseURL = 'http://127.0.0.1:8080'

const router = useRouter()

// 左眼图片数据
const leftEyeImageUrl = ref('')   //本地预览URL
const leftEyeFilePath = ref('')    //保存完整的路径
const leftEyeFileName = ref('')    //原始文件名   显示
const leftEyeSelectedFile = ref<File | null>(null)    //文件对象  用于上传

// 右眼图片数据
const rightEyeImageUrl = ref('')
const rightEyeFilePath = ref('')
const rightEyeFileName = ref('')
const rightEyeSelectedFile = ref<File | null>(null)

// 预测结果相关
const chartRef = ref<HTMLElement | null>(null)     //图表DOM引用
let chart: echarts.ECharts | null = null          //初始化ECharts实例
const probabilities = ref<Record<string, string>>({})  //预测概率字典
const showResult = ref(false)           //是否显示结果
const chartLoading = ref(false)         //图表加载中

// 计算最大概率诊断结果
const diagnosisResult = computed(() => {
  //没有概率数据返回空
  if (!probabilities.value || Object.keys(probabilities.value).length === 0) {
    return ''
  }
  //找出最大概率的键和值
  let maxKey = ''
  let maxValue = 0
  for (const [key, value] of Object.entries(probabilities.value)) {
    const numValue = parseFloat(value)
    if (numValue > maxValue) {
      maxValue = numValue
      maxKey = key
    }
  }
  
  return `${maxKey} (${maxKey === '正常' ? 'Normal' : 'Abnormal'})`
})

// 动态设置结果颜色
const resultColor = computed(() =>
  diagnosisResult.value.includes('正常') ? '#67C23A' : '#F56C6C'
)

// 性别年龄数据
const gender = ref<'male' | 'female' | ''>('')
const age = ref('')

//图表初始化
const updateChart = () => {
  if (!chart || !probabilities.value) return  

  //对概率进行排序（从高到低）
  const sortedEntries = Object.entries(probabilities.value)
    .sort((a, b) => parseFloat(b[1]) - parseFloat(a[1]))
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },     //提示框
    xAxis: {
      type: 'value',
      axisLabel: { formatter: '{value}' }
    },     //X轴    概率值
    yAxis: {
      type: 'category',
      data: sortedEntries.map(item => item[0])
    },     //Y轴    诊断类型
    series: [
      {
        name: '概率',
        type: 'bar',
        data: sortedEntries.map(item => parseFloat(item[1])),
        itemStyle: {
          color: (params: { dataIndex: number }) => 
            sortedEntries[params.dataIndex][0] === '正常' ? '#67C23A' : '#F56C6C'
        },
        label: {     // 显示数据标签
          show: true,
          position: 'right',
          formatter: (params: any) => params.value.toFixed(4)
        }
      }
    ]
  }
  chart.setOption(option)    //应用配置
}


// 核心：页面加载时检查登录状态     生命周期钩子
onMounted(() => {
  const token = localStorage.getItem('access_token')
  if (!token) {
    router.push('/login')      // 未登录，跳转到登录页面
  }
})

//销毁图表实例 释放资源
onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
})

// 左眼上传处理
const handleLeftEyeUpload = async (file: UploadFile) => {
  const rawFile = file.raw as File          //获取原始文件对象
  leftEyeSelectedFile.value = rawFile       //保存文件对象
  
  // 前端预览
  const reader = new FileReader()
  reader.onload = (e) => {
    leftEyeImageUrl.value = e.target?.result as string    //转换为DataURL
  }
  reader.readAsDataURL(rawFile)    //异步读取文件

  try {
    //构建表单数据
    const formData = new FormData()
    formData.append('file', rawFile)
    
    // 核心：自动携带token（由拦截器处理）   上传到后端
    const res = await axios.post('/detection/upload/left', formData, {
      headers: { 'Content-Type': 'multipart/form-data' } //文件上传类型
    })

    // 获取后端返回的图片路径和文件名
    leftEyeFilePath.value = res.data.image_path 
    leftEyeFileName.value = `C:\\fakepath\\${rawFile.name}`
    ElMessage.success('左眼图片上传成功')
  } catch (err) {
    ElMessage.error('左眼上传失败：' + (err as any).response?.data?.detail || '网络异常')
  }
}

// 右眼上传处理
const handleRightEyeUpload = async (file: UploadFile) => {
  const rawFile = file.raw as File
  rightEyeSelectedFile.value = rawFile
  
  // 前端预览
  const reader = new FileReader()
  reader.onload = (e) => {
    rightEyeImageUrl.value = e.target?.result as string
  }
  reader.readAsDataURL(rawFile)

  try {
    const formData = new FormData()
    formData.append('file', rawFile)
    
    // 核心：自动携带token（由拦截器处理）
    const res = await axios.post('/detection/upload/right', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    rightEyeFilePath.value = res.data.image_path 
    rightEyeFileName.value = `C:\\fakepath\\${rawFile.name}`
    ElMessage.success('右眼图片上传成功')
  } catch (err) {
    ElMessage.error('右眼上传失败：' + (err as any).response?.data?.detail || '网络异常')
  }
}


const goToUserPage = () => {
  router.push('/user')
}
// 提交预测
const submitForm = async () => {
  // 核心：校验登录状态
  const token = localStorage.getItem('access_token')
  if (!token) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  
  // 其他校验...
  if (!leftEyeFilePath.value || !rightEyeFilePath.value) {
    ElMessage.error('请先上传左右眼图片并确保上传成功')
    return
  }
  if (!gender.value) {
    ElMessage.error('请选择性别')
    return
  }
  if (!age.value || isNaN(Number(age.value)) || Number(age.value) <= 0) {
    ElMessage.error('请输入有效的年龄')
    return
  }

      try {
        // 构造预测请求体
        const requestBody = {
          left_eye: { image_path: leftEyeFilePath.value,eye_type: 'left' },
          right_eye: { image_path: rightEyeFilePath.value,eye_type: 'right' },
          age: Number(age.value),
          sex: gender.value,
        }

        // 核心：自动携带token（由拦截器处理）  发送预测请求
        const response = await axios.post('/detection/predict', requestBody)
        if (response.data.message === '检测成功') { 
          ElMessage.success('检测成功！')
          // 先更新数据
          probabilities.value = response.data.result.probabilities
          showResult.value = true   //显示结果
          
          // 确保DOM更新完成
          await nextTick()
          
          // 初始化或更新图表
          chartLoading.value = true
          try {
            //初始化图表
            if (!chart && chartRef.value) {
              chart = echarts.init(chartRef.value)
              //监听窗口大小变化，自动调整图表
              window.addEventListener('resize', () => {
                if (chart && !chart.isDisposed()) {
                  chart.resize()
                }
              })
            } else if (chart && !chart.isDisposed()) {

              chart.dispose()
              chart = echarts.init(chartRef.value)
            }
            updateChart()
            
          } catch (error) {
            console.error('图表初始化失败:', error)
            ElMessage.error('图表初始化失败，请刷新页面重试')
            return
          } finally {
            chartLoading.value = false
          }
          
        } else {
          ElMessage.error('检测失败：' + response.data.message)
        }
  } catch (error) {
    console.error('预测请求出错：', error)
    ElMessage.error('检测失败，请稍后重试')
  }
}
</script>

<template>
  <div class="upload-container">
    <h1 class="gradient-title">眼部是否患病实时分类预测</h1>
    
    <!-- 上传区域 -->
    <div class="upload-section">
      <!-- 左眼上传 -->
      <div class="eye-upload">
        <span class="upload-label">左眼:</span>
        <div class="custom-upload">
          <input
            type="text" 
            class="custom-upload-input" 
            :value="leftEyeFileName" 
            readonly   
          />
          <el-upload     
            class="upload-demo"
            action="#"   
            :on-change="handleLeftEyeUpload"  
            :auto-upload="false"   
            :show-file-list="false"  
            accept="image/*"   
          >
            <el-button type="primary">浏览文件</el-button>
          </el-upload>
        </div>
      </div>
      
      <!-- 右眼上传 -->
      <div class="eye-upload">
        <span class="upload-label">右眼:</span>
        <div class="custom-upload">
          <input
            type="text" 
            class="custom-upload-input" 
            :value="rightEyeFileName" 
            readonly   
          />
          <el-upload     
            class="upload-demo"
            action="#"   
            :on-change="handleRightEyeUpload"  
            :auto-upload="false"   
            :show-file-list="false"  
            accept="image/*"   
          >
            <el-button type="primary">浏览文件</el-button>
          </el-upload>
        </div>
      </div>
      
      <!-- 性别年龄 -->
      <div class="gender-age-section">
        <span class="upload-label">性别:</span>
        <el-radio-group v-model="gender">
          <el-radio label="male">男</el-radio>
          <el-radio label="female">女</el-radio>
        </el-radio-group>
        
        <span class="upload-label" style="margin-left: 20px;">年龄:</span>
        <el-input 
          v-model="age" 
          placeholder="请输入年龄" 
          style="width: 120px; margin-left: 8px;"
        />
      </div>
      
      <!-- 提交按钮 -->
      <el-button 
        type="success" 
        @click="submitForm" 
        style="margin-left: 15px;"
      >
        提交预测
      </el-button>
      <el-button 
        type="primary" 
        @click="goToUserPage"
        style="margin-left: 15px;"
      >
        返回我的主页
      </el-button>
    </div>

    <!-- 预览区域 -->
    <div class="preview-section">
      <!-- 左眼预览 -->
      <div 
        class="image-preview" 
        :class="{ empty: !leftEyeImageUrl }"
      >
        <img 
          v-if="leftEyeImageUrl" 
          :src="leftEyeImageUrl" 
          alt="左眼预览图片" 
        />
        <span v-else>请上传左眼图片进行预览</span>
      </div>

      <!-- 右眼预览 -->
      <div 
        class="image-preview" 
        :class="{ empty: !rightEyeImageUrl }"
        style="margin-left: 20px;"
      >
        <img 
          v-if="rightEyeImageUrl" 
          :src="rightEyeImageUrl" 
          alt="右眼预览图片" 
        />
        <span v-else>请上传右眼图片进行预览</span>
      </div>
    </div>

    <!-- 结果展示区域 -->
    <div class="result-section" v-if="showResult">
      <h2 :style="{ color: resultColor }">预测结果: {{ diagnosisResult }}</h2>
      
      <h3>模型预测概率分布</h3>
      <div ref="chartRef" class="chart-container">
        <div v-if="chartLoading" class="chart-loading">
          <div class="loading-spinner"></div>
          <p>图表加载中...</p>
        </div>
      </div>
      
      <div class="result-details">
        <div class="details-header">
          <h4>诊断建议:</h4>
          <span 
            class="status-tag" 
            :class="{ 'normal': diagnosisResult.includes('正常'), 'abnormal': !diagnosisResult.includes('正常') }"
          >
            {{ diagnosisResult.includes('正常') ? '正常' : '异常' }}
          </span>
        </div>
        <p v-if="diagnosisResult.includes('正常')">
          您的眼部状况正常，建议每年进行一次常规检查，重点关注眼压、眼底视网膜等基础项目。
        </p>
        <p v-else>
          检测到异常情况，建议 <strong>72 小时内</strong> 预约专业眼科医生，进行 OCT 断层扫描、视野检查等详细检测。
        </p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.upload-container {
  width: 1200px; 
  max-width: 100%; 
  margin: 5px auto;  
  padding: 40px 20px; 
  background: #fff;  
  border-radius: 12px;  
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.05);   
  display: flex;   
  flex-direction: column;   
  align-items: flex-start; 
}

.gradient-title {
  font-size: 28px;
  margin-bottom: 35px;  
  background: linear-gradient(90deg, #165DFF 0%, #36D399 100%);
  -webkit-background-clip: text;  
  background-clip: text;   
  color: transparent;   
  text-shadow: 0 2px 10px rgba(22, 93, 255, 0.1);  
}

h1 {
  font-size: 24px;
  margin-bottom: 30px;  
  color: #333;   
}

.upload-section {
  display: flex;   
  flex-wrap: wrap; 
  align-items: center;   
  margin-bottom: 30px;   
}

.eye-upload {
  display: flex;
  align-items: center;
  margin-right: 30px;
  margin-bottom: 15px;
}

.upload-label {
  margin-right: 15px;   
  font-size: 16px;
  color: #333;   
}

.custom-upload {
  display: flex;    
  align-items: center;   
  margin-right: 15px; 
}

.custom-upload-input {
  padding: 6px 12px;   
  border: 1px solid #dcdcdc;  
  border-radius: 4px;   
  margin-right: 8px;   
  cursor: default;    
  background-color: #fff;   
  color: #333;   
  width: 300px;   
}

.upload-demo {
  margin-right: 15px;   
}

.gender-age-section {
  display: flex;
  align-items: center;
  margin-right: 30px;
  margin-bottom: 15px;
}

.preview-section {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  min-height: 400px;  
}

.image-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 360px;
  height: 360px;
  border-radius: 8px;    
  background: #fcfcfc;   
  margin-right: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.image-preview.empty {
  border: 1px dashed #ddd;
  color: #999;
  font-size: 16px;
}

.image-preview img {
  max-width: 100%;    
  max-height: 100%;  
  border-radius: 8px;   
}

.el-button {
  transition: all 0.3s ease;   
}

.el-button:hover {
  transform: translateY(-2px);    
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);   
}

/* 结果区域样式 */
.result-section {
  width: 100%;
  margin-top: 40px;
  padding: 30px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.05);
}

h2 {
  font-size: 20px;
  margin-bottom: 20px;
}

h3 {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
}

.chart-container {
  width: 100%;
  height: 400px;
  margin: 20px 0;
  position: relative;
}

.chart-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.result-details {
  margin-top: 30px;
  padding: 20px 24px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  font-size: 14px;
  line-height: 1.7;
  color: #555;
}

.details-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.details-header h4 {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.status-tag {
  margin-left: 8px;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.normal {
  background-color: #e6f8e2;
  color: #4caf50; 
  border: 1px solid #d3eecf;
}

.status-tag.abnormal {
  background-color: #fff3f0;
  color: #f44336; 
  border: 1px solid #fadada;
}

.result-details p {
  margin: 0;
  text-indent: 2em;
}

.result-details p strong {
  color: #f44336;
  font-weight: 600;
}
</style>